<template>
  <n-layout-header>
    <div class="design-header">
      <n-space style="float:right;">
        <n-button @click="toJson(true)">清空</n-button>
        <n-button @click="toJson(true)">下载options.js</n-button>
        <n-button @click="toJson(true)">下载form.vue</n-button>
        <n-button @click="preview">预览</n-button>
      </n-space>
    </div>
  </n-layout-header>
  <n-modal
    v-model:show="showModal"
    style="width:800px"
    preset="dialog"
    title="预览"
  >
  <generate-form :fields="fields" :formOption="formOption" :rules="rules" :form="form" />
  </n-modal>
</template>

<script>
import { saveJson, saveText, jsonToStr } from "../../utils/jsonUtil";
import { useStore } from "vuex";
import {ref} from 'vue'
import GenerateForm from '../../components/GenerateForm.vue';
import _ from 'lodash'
export default {
  components: { GenerateForm },
  setup() {
    const store = useStore();
    let formOption=ref({})
    let fields = ref([])
    let rules = ref({})

    const toJson = (save) => {
      let fs = _.cloneDeep([...store.state.fields]);
      let arr = [];
      for (let i = 0; i < fs.length; i++) {
        let obj = _.cloneDeep({ ...fs[i] });
        delete obj.selected;
        delete obj.rule;
        delete obj.widget.attr;
        Object.assign(obj, { ...obj.widget });
        delete obj.widget;
        arr.push({...obj});
      }
      let json =
        "export default " +
        jsonToStr({
          formOption: _.cloneDeep({ ...store.state.form }),
          fields: arr,
          rules: _.cloneDeep({ ...store.state.rules }),
        });
        fields.value = [...arr]
        rules.value = { ...store.state.rules }
        formOption.value = { ...store.state.form }
      json = json
        .replace(/\"function/g, "function")
        .replace(/\\n/g, "")
        .replace(/}\"/g, "}")
        .replace(/\\\\/g, "\\")
        .replace(/\\\"/g,"\"")
      if (save) {
        saveJson(json, "options.js")
      }
    };
    const showModal = ref(false)
    const preview = () => {
      toJson(false)
      console.log(formOption,rules,fields)
      showModal.value=true
    }
    const form = ref({})
    
    return {
      toJson,preview,showModal,form,formOption,rules,fields
    };
  },
};
</script>

<style scoped>
.design-header {
  line-height: 50px;
  height: 50px;
  padding: 0 10px;
}
</style>
